package com.syty.demo.Listener;

import com.sun.deploy.net.HttpRequest;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashMap;
import java.util.Map;

public class LoginSessionListener implements HttpSessionListener {
    // 存储已登录用户的Session ID
    private static Map<String, HttpSession> loginSessions = new HashMap<>();

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        String sessionId = session.getId();
        System.out.println("Session created: " + sessionId);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        String sessionId = session.getId();
        // 从map中移除对应的Session ID
        loginSessions.remove(sessionId);
        System.out.println("Session destroyed: " + sessionId);
    }

    /**
     * 判断用户是否已经登录
     * @param sessionId 用户Session ID
     * @return 是否已经登录
     */
    public static boolean hasLogin(String sessionId) {
        return loginSessions.containsKey(sessionId);
    }

    /**
     * 用户登录成功后，将Session ID存储到map中
     * @param sessionId 用户Session ID
     * @param session HttpSession
     */
    public static void addSession(String sessionId, HttpSession session) {
        loginSessions.put(sessionId, session);
    }

    /**
     * 用户退出登录或者Session过期时，从map中移除对应的Session ID
     * @param sessionId 用户Session ID
     */
    public static void removeSession(String sessionId) {
        loginSessions.remove(sessionId);
    }
}

